// eslint-disable-next-line import/no-commonjs
const vscode = require('vscode');
// eslint-disable-next-line import/no-commonjs
const fs = require('fs');
// eslint-disable-next-line import/no-commonjs
const path = require('path');
const { console } = require('inspector');

function activate(context) {
  let disposable = vscode.commands.registerCommand('extension.createTaroPage', async function () {
    const pageName = await vscode.window.showInputBox({
      prompt: '请输入页面名称',
      placeHolder: '例如：home'
    });

    if (!pageName) return;

    // 将页面名称首字母大写
    const formattedPageName = pageName.charAt(0).toUpperCase() + pageName.slice(1);

    const workspaceFolders = vscode.workspace.workspaceFolders;
    if (!workspaceFolders) {
      vscode.window.showErrorMessage('请先打开一个工作区');
      return;
    }

    const workspacePath = workspaceFolders[0].uri.fsPath;
    const pagesPath = path.join(workspacePath, 'src', 'pages');
    const newPagePath = path.join(pagesPath, pageName);

    try {
      // 创建页面目录
      fs.mkdirSync(newPagePath, { recursive: true });

      // 创建页面文件
      const template = `import React from 'react';
import { View, Text } from '@tarojs/components';
import './index.scss';

const ${formattedPageName} = () => {
  return (
    <View className="rui-${pageName}-page-content">
      <Text>${pageName}页面</Text>
    </View>
  );
};

export default ${formattedPageName};`;

      fs.writeFileSync(path.join(newPagePath, 'index.jsx'), template);
      const styleTemplate = `.rui-${pageName}-page-content {\n  padding: 20px;\n}\n`;      
      fs.writeFileSync(path.join(newPagePath, 'index.scss'), styleTemplate);

      // 创建页面配置文件
      const configTemplate = `export default {
  navigationBarTitleText: '${pageName}页面'
};
`;
      fs.writeFileSync(path.join(newPagePath, 'index.config.js'), configTemplate);

      // 更新app.config.js
      const appConfigPath = path.join(workspacePath, 'src', 'app.config.js');
      const appConfigContent = fs.readFileSync(appConfigPath, 'utf8');
      const pagesRegex = /pages:\s*\[([\s\S]*?)\]/;
      const match = appConfigContent.match(pagesRegex);
      if (match) {
        const pagesArray = match[1].trim();
        const newPages = pagesArray + (pagesArray ? ',\n    ' : '') + `"pages/${pageName}/index"`;
        const newAppConfigContent = appConfigContent.replace(pagesRegex, `pages: [\n    ${newPages}\n  ]`);
        fs.writeFileSync(appConfigPath, newAppConfigContent);
      }

      vscode.window.showInformationMessage(`页面 ${pageName} 创建成功！`);
    } catch (error) {
      vscode.window.showErrorMessage(`创建页面失败：${error.message}`);
    }
  });
  context.subscriptions.push(disposable);
}

function deactivate() {}

module.exports = {
  activate,
  deactivate
};